package us.team.openAnAppAtRandom;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Display;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Black mask layer service
 * Creates a system-level overlay that covers the entire screen
 * Shows black background and "Untouch" text
 */
public class MaskService extends Service {
    
    private WindowManager windowManager;
    private View overlayView;
    private PowerManager.WakeLock wakeLock; // 用于保持屏幕常亮
    
    // 用于检测Z字手势
    private Path gesturePath;
    private Path zTemplatePath;
    private float startX, startY;
    private boolean isDrawing = false;
    
    // Z字模板的点
    private Point[] zPoints = new Point[4];
    
    // 用于跟踪用户是否经过了Z字的关键点
    private boolean[] pointsPassed = new boolean[4];
    private float touchThreshold = 100; // 触摸判定阈值（像素）
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        // 获取窗口管理器
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        
        // 获取电源管理器并创建WakeLock，保持屏幕常亮
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK | 
                PowerManager.ACQUIRE_CAUSES_WAKEUP | 
                PowerManager.ON_AFTER_RELEASE, "MaskService:WakeLock");
        wakeLock.acquire(); // 获取WakeLock，保持屏幕常亮
        
        // 创建遮罩层视图
        createOverlayView();
        
        // 添加遮罩层到窗口
        addOverlayToWindow();
    }
    
    /**
     * Create overlay view
     */
    private void createOverlayView() {
        // Create root layout
        FrameLayout rootLayout = new FrameLayout(this);
        rootLayout.setBackgroundColor(Color.BLACK); // Set black background
        
        // 设置布局参数，确保覆盖整个屏幕包括系统UI
        rootLayout.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
                View.SYSTEM_UI_FLAG_FULLSCREEN |
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                View.SYSTEM_UI_FLAG_LOW_PROFILE |
                View.SYSTEM_UI_FLAG_IMMERSIVE
        );
        
        // 创建一个专门用于覆盖导航栏的视图
        View navBarCover = new View(this);
        navBarCover.setBackgroundColor(Color.BLACK);
        
        // 获取屏幕尺寸
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int screenWidth = size.x;
        int screenHeight = size.y;
        
        // 创建Z字模板路径
        createZTemplate(screenWidth, screenHeight);
        
        // Create "Untouch" text
        TextView untouchText = new TextView(this);
        untouchText.setText("Untouch");
        untouchText.setTextColor(Color.argb(50, 255, 255, 255)); // Light color text
        untouchText.setTextSize(30); // Large font size
        
        // Set text to center
        FrameLayout.LayoutParams textParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
        );
        textParams.gravity = Gravity.CENTER;
        
        // Add text to layout
        rootLayout.addView(untouchText, textParams);
        
        // 添加导航栏覆盖层
        Display displayNav = windowManager.getDefaultDisplay();
        Point sizeNav = new Point();
        displayNav.getRealSize(sizeNav);
        
        // 获取导航栏高度
        int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        int navBarHeight = resourceId > 0 ? getResources().getDimensionPixelSize(resourceId) : 0;
        
        // 创建导航栏覆盖视图
        View navBarCoverView = new View(this);
        navBarCoverView.setBackgroundColor(Color.BLACK);
        
        // 根据设备方向设置导航栏覆盖层位置
        FrameLayout.LayoutParams navBarParams;
        if (sizeNav.x > sizeNav.y) { // 横屏
            navBarParams = new FrameLayout.LayoutParams(navBarHeight, sizeNav.y);
            navBarParams.gravity = Gravity.RIGHT;
        } else { // 竖屏
            navBarParams = new FrameLayout.LayoutParams(sizeNav.x, navBarHeight);
            navBarParams.gravity = Gravity.BOTTOM;
        }
        
        rootLayout.addView(navBarCoverView, navBarParams);
        
        // 创建状态栏覆盖视图
        int statusBarHeight = 0;
        int statusBarResourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (statusBarResourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(statusBarResourceId);
        }
        
        View statusBarCover = new View(this);
        statusBarCover.setBackgroundColor(Color.BLACK);
        FrameLayout.LayoutParams statusBarParams = new FrameLayout.LayoutParams(size.x, statusBarHeight);
        statusBarParams.gravity = Gravity.TOP;
        
        rootLayout.addView(statusBarCover, statusBarParams);
        
        // 初始化手势路径
        gesturePath = new Path();
        
        // 创建自定义视图来绘制Z字模板和用户的手势轨迹
        final View gestureView = new View(this) {
            Paint userPaint = new Paint();
            Paint templatePaint = new Paint();
            
            {
                userPaint.setColor(Color.argb(100, 255, 255, 255));
                userPaint.setStyle(Paint.Style.STROKE);
                userPaint.setStrokeWidth(15);
                userPaint.setStrokeJoin(Paint.Join.ROUND);
                userPaint.setStrokeCap(Paint.Cap.ROUND);
                
                templatePaint.setColor(Color.argb(40, 255, 255, 255));
                templatePaint.setStyle(Paint.Style.STROKE);
                templatePaint.setStrokeWidth(30);
                templatePaint.setStrokeJoin(Paint.Join.ROUND);
                templatePaint.setStrokeCap(Paint.Cap.ROUND);
            }
            
            @Override
            protected void onDraw(Canvas canvas) {
                super.onDraw(canvas);
                // 绘制Z字模板
                canvas.drawPath(zTemplatePath, templatePaint);
                // 不再绘制用户手势轨迹
                // canvas.drawPath(gesturePath, userPaint);
            }
        };
        
        // 添加手势视图到布局
        rootLayout.addView(gestureView, new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                FrameLayout.LayoutParams.MATCH_PARENT
        ));
        
        // 拦截所有触摸事件并检测Z字手势
        rootLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                float x = event.getX();
                float y = event.getY();
                
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 开始新的手势
                        gesturePath.reset();
                        gesturePath.moveTo(x, y);
                        isDrawing = true;
                        
                        // 重置点通过状态
                        resetPointsPassed();
                        
                        // 检查是否在起点附近
                        checkPointPassed(0, x, y);
                        break;
                        
                    case MotionEvent.ACTION_MOVE:
                        if (isDrawing) {
                            // 继续绘制路径
                            gesturePath.lineTo(x, y);
                            
                            // 检查是否经过了Z字的关键点
                            for (int i = 0; i < zPoints.length; i++) {
                                checkPointPassed(i, x, y);
                            }
                            
                            // 检查是否完成了Z字轨迹
                            if (allPointsPassed()) {
                                // Z字已完成，关闭遮罩层并退出程序
                                Toast.makeText(MaskService.this, "Z字轨迹已完成，退出程序", Toast.LENGTH_SHORT).show();
                                stopSelf();
                                // 退出整个应用程序
                                System.exit(0);
                            }
                            
                            // 刷新视图以显示路径
                            gestureView.invalidate();
                        }
                        break;
                        
                    case MotionEvent.ACTION_UP:
                        isDrawing = false;
                        // 如果没有完成Z字，重置路径
                        if (!allPointsPassed()) {
                            gesturePath.reset();
                            resetPointsPassed();
                            gestureView.invalidate();
                        }
                        break;
                }
                
                // 返回true表示消费了事件，不会传递到下层应用
                return true;
            }
        });
        
        overlayView = rootLayout;
    }
    
    /**
     * Add overlay to window
     */
    private void addOverlayToWindow() {
        // Create window layout parameters
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT,
                // 使用最高级别的窗口类型来覆盖系统UI
                (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 
                    ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 
                    : (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
                        ? WindowManager.LayoutParams.TYPE_SYSTEM_ERROR // 在Android 4.4-7.1使用系统错误窗口类型
                        : WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
                WindowManager.LayoutParams.FLAG_FULLSCREEN |
                WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS |
                WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
                WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS |
                WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                PixelFormat.OPAQUE // 使用不透明背景确保完全覆盖
        );
        
        // 设置窗口位置为全屏，包括状态栏和导航栏区域
        params.gravity = Gravity.TOP | Gravity.LEFT;
        params.x = 0;
        params.y = 0;
        
        // 获取屏幕尺寸并设置窗口大小
        Display display = windowManager.getDefaultDisplay();
        Point size = new Point();
        display.getRealSize(size); // 获取真实屏幕尺寸，包括系统UI区域
        params.width = size.x;
        params.height = size.y;
        
        // Add view to window
        windowManager.addView(overlayView, params);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        
        // 释放WakeLock
        if (wakeLock != null && wakeLock.isHeld()) {
            wakeLock.release();
            wakeLock = null;
        }
        
        // 移除遮罩层
        if (overlayView != null && windowManager != null) {
            windowManager.removeView(overlayView);
            overlayView = null;
        }
    }
    
    /**
     * 创建Z字模板路径
     */
    private void createZTemplate(int screenWidth, int screenHeight) {
        // 初始化Z字模板路径
        zTemplatePath = new Path();
        
        // 计算Z字的四个关键点
        int margin = screenWidth / 6;
        int topY = screenHeight / 5; // 更高的起点，接近屏幕顶部
        int bottomY = screenHeight * 4 / 5; // 更低的终点，接近屏幕底部
        
        // 左上角
        zPoints[0] = new Point(margin, topY);
        // 右上角
        zPoints[1] = new Point(screenWidth - margin, topY);
        // 左下角（对角线中间点）
        zPoints[2] = new Point(margin, bottomY);
        // 右下角
        zPoints[3] = new Point(screenWidth - margin, bottomY);
        
        // 创建Z字路径
        zTemplatePath.moveTo(zPoints[0].x, zPoints[0].y);
        zTemplatePath.lineTo(zPoints[1].x, zPoints[1].y);
        zTemplatePath.lineTo(zPoints[2].x, zPoints[2].y);
        zTemplatePath.lineTo(zPoints[3].x, zPoints[3].y);
    }
    
    /**
     * 重置所有点的通过状态
     */
    private void resetPointsPassed() {
        for (int i = 0; i < pointsPassed.length; i++) {
            pointsPassed[i] = false;
        }
    }
    
    /**
     * 检查用户是否经过了指定的点
     */
    private void checkPointPassed(int pointIndex, float x, float y) {
        if (pointIndex < 0 || pointIndex >= zPoints.length) return;
        
        // 计算用户触摸点与Z字关键点的距离
        float distance = (float) Math.sqrt(
                Math.pow(x - zPoints[pointIndex].x, 2) + 
                Math.pow(y - zPoints[pointIndex].y, 2));
        
        // 如果距离小于阈值，标记为已通过
        if (distance < touchThreshold) {
            pointsPassed[pointIndex] = true;
        }
    }
    
    /**
     * 检查是否所有点都已通过
     */
    private boolean allPointsPassed() {
        for (boolean passed : pointsPassed) {
            if (!passed) return false;
        }
        return true;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Restart service if killed
        return START_STICKY;
    }
}